package com.yzqp.blog.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.yzqp.common.log.LogUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class BaseInterceptor implements HandlerInterceptor {

    public void responseWrite(HttpServletResponse response, Object o) {
        try {
            responseWrite(response, 200, o);
        } catch (Exception e) {
            LogUtil.getBean().error(e.getMessage());
        }
    }

    public void responseWrite(HttpServletResponse response, int status, Object o) throws Exception {
        //解决中文乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(status);
        //获得写的类
        PrintWriter out = response.getWriter();
        //将object改为json字符串格式
        out.println(JSONObject.toJSONString(o));
        out.flush();
        out.close();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
